package cn.qiyu5522.tk_ems.service.impl;

import cn.qiyu5522.tk_ems.entity.RoleMenu;
import cn.qiyu5522.tk_ems.mapper.RoleMenuMapper;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色-菜单关联表 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-02-27
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {


    @Resource
    private ObjectMapper objectMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R editByRowId(Integer roleId, List<Integer> menuIds) {
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.eq(RoleMenu::getRoleId, roleId);
        // 先删除
        baseMapper.delete(roleMenuLambdaQueryWrapper);
        // 在插入
        List<RoleMenu> roleMenus = new ArrayList<>(menuIds.size());
        RoleMenu roleMenu = null;
        if (menuIds.size() != 0) {
            for (Integer menuId : menuIds) {
                roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                roleMenus.add(roleMenu);
            }
            baseMapper.insertBatchSomeColumn(roleMenus);

        }
        return R.ok().message("更新成功");
    }
}
